package com.example.its2021606134chh.BusModule;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.its2021606134chh.HttpUtil;
import com.example.its2021606134chh.MyMessageModule.ListViewAdapter;
import com.example.its2021606134chh.R;
import com.example.its2021606134chh.TrafficViolationModule.CarPeccancy;
import com.example.its2021606134chh.TrafficViolationModule.CarSQLiteOpenHelper;
import com.example.its2021606134chh.TrafficViolationModule.TVSearchResultsActivity;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class BusLineActivity extends AppCompatActivity {

    private ImageView imgBusLineBack;
    private TextView tvBusLineName;
    private TextView tvBusLinePlace;
    private TextView tvBusLineStartTime;
    private TextView tvBusLineEndTime;
    private ImageView imgBusLineReturn;
    private TextView tvBusStaticDistance;
    private TextView tvBusLinePrice;
    private ListView lvBusLinePlaceList;
    private String sBusLineNum;
    public static SharedPreferences sp;
    private int id;
    private String busline_name;
    private String start_place;
    private String end_place;
    private String start_place_start_time;
    private String start_place_end_time;
    private String end_place_start_time;
    private String end_place_end_time;
    private int price;
    private String route;
    private List<String> list = new ArrayList<>();
    private BusListViewAdapter adapter;
    private Boolean isCheck = true;
    BusSQLiteOpenHelper openHelper;
    BusHistorySQLiteOpenHelper historyOpenHelper;
    SQLiteDatabase database;
    SQLiteDatabase database2;

    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bus_line);
        Intent intent = getIntent();
        String getBusLineNum = intent.getStringExtra("BusLineNum");
        if (getBusLineNum.startsWith("10")) {   //101 102 103
            sBusLineNum = getBusLineNum + "路线";
        } else {
            sBusLineNum = "汽车站快线";
        }
        Log.i("TAG", sBusLineNum);

        openHelper = new BusSQLiteOpenHelper(BusLineActivity.this, "BusLine.db", null, 1);

        sp = getSharedPreferences("BusLine", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        int x = sp.getInt("BusF",1);
        if (x == 1)
        {
            Log.i("TAG", "BusF");
            x++;
            editor.putInt("BusF",x);
            editor.commit();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    HttpUtil.asyncRequest(new HttpUtil.AsyncCallBack() {
                        @Override
                        public void onFailure(Exception e) {

                        }

                        @RequiresApi(api = Build.VERSION_CODES.O)
                        @Override
                        public void onResponse(String json) {
                            Gson gson = new Gson();
                            BusLine line = gson.fromJson(json, BusLine.class);
                            List<BusLine.ROWSDETAILBean> Temp = line.getROWS_DETAIL();
//                            price varchar, distance varchar, bus_stop varchar
                            for (int i = 0; i < Temp.size(); i++) {
                                ContentValues values = new ContentValues();
                                values.put("id", Temp.get(i).getId());
                                values.put("busline_name", Temp.get(i).getBusline_name());
                                values.put("start_place", Temp.get(i).getStart_place());
                                values.put("end_place", Temp.get(i).getEnd_place());
                                values.put("start_place_start_time", Temp.get(i).getStart_place_start_time());
                                values.put("start_place_end_time", Temp.get(i).getStart_place_end_time());
                                values.put("end_place_start_time", Temp.get(i).getEnd_place_start_time());
                                values.put("end_place_end_time", Temp.get(i).getEnd_place_end_time());
                                values.put("price", Temp.get(i).getPrice());
//   StringUtils.join()和String.join()：可用来把字符串数组拼接成整条字符串，效果一样只是用法稍有不同，StringUtils要引入jar包common-lang3, String.join()是JDK8新增方法。
                                List<String> routeList = Temp.get(i).getRoute();
                                String sRoute = String.join(",", routeList);
//                                Log.i("TAG", sRoute);
                                values.put("route", sRoute);
                                database = openHelper.getWritableDatabase();
                                database.insert("busline", null, values);
                                database.close();
                            }
                            Log.i("TAG", "" + Temp.size());
                        }
                    }, "get_busline_info", new String[]{"UserName"}, "user1");
                }
            }).start();
        }
        initView();

        database = openHelper.getReadableDatabase();
        try (Cursor cursor = database.query("busline", null, null, null, null, null, null)) {
            if (cursor.moveToFirst()) {
                do {
                    id = cursor.getInt(0);
                    busline_name = cursor.getString(1);
                    if (busline_name.equals(sBusLineNum)) {
                        start_place = cursor.getString(2);
                        end_place = cursor.getString(3);
                        if (end_place.equals("啥口")) {   //服务器错误
                            end_place = "沙口";
                        }
                        ContentValues values = new ContentValues();
                        values.put("id", id);
                        values.put("busline_name", busline_name);
                        values.put("start_place", start_place);
                        values.put("end_place", end_place);
                        historyOpenHelper = new BusHistorySQLiteOpenHelper(BusLineActivity.this, "bushistory.db", null, 1);
                        database2 = historyOpenHelper.getWritableDatabase();
                        database2.insert("bushistory", null, values);
                        database2.close();
                        start_place_start_time = cursor.getString(4);
                        start_place_end_time = cursor.getString(5);
                        end_place_start_time = cursor.getString(6);
                        end_place_end_time = cursor.getString(7);
                        price = cursor.getInt(8);
                        route = cursor.getString(9);
                        tvBusLinePlace.setText(start_place + " - " + end_place);
                        tvBusLineStartTime.setText(start_place_start_time);
                        tvBusLineEndTime.setText(start_place_end_time);
                        String[] arrList = route.split(",");
                        int count = 0;
                        for (String s : arrList) {
                            list.add(s);
                            count++;
                        }
                        adapter = new BusListViewAdapter(BusLineActivity.this, list);
                        lvBusLinePlaceList.setAdapter(adapter);
                        tvBusStaticDistance.setText(count + "站");
                        tvBusLinePrice.setText("最高票价" + price + "元");
                        break;
                    }
                } while (cursor.moveToNext());
            }
        } catch (SQLException ignored) {
            Toast.makeText(BusLineActivity.this, "没有查询到" + sBusLineNum + "的数据！", Toast.LENGTH_SHORT).show();
            finish();
        } finally {
            database.close();
        }

        imgBusLineBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        imgBusLineReturn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i("TAG", String.valueOf(isCheck));
                list.clear();
                if (isCheck) {
                    tvBusLinePlace.setText(end_place + " - " + start_place);
                    tvBusLineStartTime.setText(end_place_start_time);
                    tvBusLineEndTime.setText(end_place_end_time);
                    String[] arrList = route.split(",");
                    Collections.reverse(Arrays.asList(arrList));
                    list.addAll(Arrays.asList(arrList));
                    adapter = new BusListViewAdapter(BusLineActivity.this, list);
                    lvBusLinePlaceList.setAdapter(adapter);
                    isCheck = false;
                } else {
                    tvBusLinePlace.setText(start_place + " - " + end_place);
                    tvBusLineStartTime.setText(start_place_start_time);
                    tvBusLineEndTime.setText(start_place_end_time);
                    String[] arrList = route.split(",");
                    list.addAll(Arrays.asList(arrList));
                    adapter = new BusListViewAdapter(BusLineActivity.this, list);
                    lvBusLinePlaceList.setAdapter(adapter);
                    isCheck = true;
                }
            }
        });

        tvBusLineName.setText(sBusLineNum);

        lvBusLinePlaceList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                adapter.singleChoose(position);
            }
        });

    }

    private void initView() {
        imgBusLineBack = (ImageView) findViewById(R.id.imgBusLineBack);
        tvBusLineName = (TextView) findViewById(R.id.tvBusLineName);
        tvBusLinePlace = (TextView) findViewById(R.id.tvBusLinePlace);
        tvBusLineStartTime = (TextView) findViewById(R.id.tvBusLineStartTime);
        tvBusLineEndTime = (TextView) findViewById(R.id.tvBusLineEndTime);
        imgBusLineReturn = (ImageView) findViewById(R.id.imgBusLineReturn);
        tvBusStaticDistance = (TextView) findViewById(R.id.tvBusStaticDistance);
        tvBusLinePrice = (TextView) findViewById(R.id.tvBusLinePrice);
        lvBusLinePlaceList = (ListView) findViewById(R.id.lvBusLinePlaceList);
    }
}